package com.hongji.lms5xxcommunicator;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * <p>应用启动入口（Spring Boot）。</p>
 *
 * <p><b>职责：</b></p>
 * <ul>
 *   <li>启动 Spring Boot 应用（{@link SpringApplication#run(Class, String...)}）。</li>
 *   <li>注册 Web MVC 配置（静态资源映射与 SPA 路由转发）。</li>
 *   <li>扫描 MyBatis Mapper 接口（{@link MapperScan}）。</li>
 * </ul>
 *
 * <p><b>用法：</b></p>
 * <ol>
 *   <li>运行 {@link #main(String[])} 即可启动服务。</li>
 *   <li>前端静态文件放置于 <code>src/main/resources/static</code>，通过 <code>/**</code> 路径直接访问。</li>
 *   <li>未匹配的非静态路径将转发至 <code>index.html</code>（适用于单页应用前端路由）。</li>
 * </ol>
 *
 * @since 1.0
 */
@SpringBootApplication
@MapperScan("com.hongji.lms5xxcommunicator.mapper")
public class Lms5xxCommunicatorApplication {

    /** 静态日志器（main 为静态方法，故使用静态 logger） */
    private static final Logger LOG = LoggerFactory.getLogger(Lms5xxCommunicatorApplication.class);

    public static void main(String[] args) {
        LOG.info("应用启动中……");
        ConfigurableApplicationContext ctx = SpringApplication.run(Lms5xxCommunicatorApplication.class, args);

        // 启动关键信息打印
        Environment env = ctx.getEnvironment();
        String port = env.getProperty("server.port", "8080");
        String contextPath = env.getProperty("server.servlet.context-path", "");
        LOG.info("启动完成：port={}，contextPath='{}'，静态资源=classpath:/static/", port, contextPath);

        // 优雅停机提示
        Runtime.getRuntime().addShutdownHook(new Thread(() -> LOG.info("应用即将停止（JVM shutdown hook）")));
    }

    /**
     * <p>Web MVC 配置。</p>
     *
     * <p><b>内容：</b></p>
     * <ul>
     *   <li>静态资源映射：<code>/** → classpath:/static/</code>（{@link ResourceHandlerRegistry}）。</li>
     *   <li>SPA 路由转发：未匹配的非静态路径转发至 <code>index.html</code>（{@link ViewControllerRegistry}）。</li>
     * </ul>
     *
     * @return WebMvcConfigurer Bean
     * @see WebMvcConfigurer
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer() { // 原名 corsConfigurer；更名以语义更准确
        return new WebMvcConfigurer() {

            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                // 静态资源映射（确保前端静态文件能够被直接访问）
                registry.addResourceHandler("/**")
                        .addResourceLocations("classpath:/static/");
                LOG.info("已注册静态资源映射：/** → classpath:/static/");
            }

            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // 将所有未匹配的“非点号路径”转发到 index.html，用于前端 SPA 路由
                registry.addViewController("/{path:^(?!stream|sockjs|app|topic)[^\\.]*$}")
                        .setViewName("forward:/index.html");
                LOG.info("已注册 SPA 路由转发：/{path:[^\\.]*} → forward:/index.html");
            }
        };
    }
}
